package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.badibadi.adapter.ClubMyClubListAdapter;
import com.badibadi.adapter.Popwindows_Adapter;
import com.badibadi.infos.ClubMy_Model;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.miloisbadboy.view.PullToRefreshView;
import com.miloisbadboy.view.PullToRefreshView.OnFooterRefreshListener;
import com.miloisbadboy.view.PullToRefreshView.OnHeaderRefreshListener;

public class MyClubFragment0 extends BaseFragment implements
		OnHeaderRefreshListener, OnFooterRefreshListener {
	String TAG = "MyClubFragment0";
	static MyClubFragment0 myClubFragment0;
	private GridView gv;
	private PullToRefreshView mPullToRefreshView;
	private int Page;
	private List<ClubMy_Model> clubModels;
	private List<ClubMy_Model> list;// 临时存放数据的
	private String type = "0";// 0最新 1最火 2自创
	private ClubMyClubListAdapter clubMyClubListAdapter;
	private List<ClueTypeModel> clueTypeModels;
	private ListView type_list;
	private Popwindows_Adapter popwindows_Adapter;
	private LinearLayout fragment_club_overview0_btn_type_xgridview;
	private LinearLayout xgridview_search;
	private String uid = "26";// 用户id
	private String fid = "-1";// 朋友id——26
	private String tid = null;// 类别id
	private String searchName = null;// 关键字搜索
	private int pageNum = 10;// 每页数量
	private boolean isReturnUp = true;// 按返回键是否回退关键字
	private boolean isSouSuo1 = true;
	private boolean isSouSuo2 = true;
	private Message message;
	private Bundle bundle;
	private TextView xgridview_TheKeyword;
	private LinearLayout xgridview_keyword_kuang;

	private List<Integer> listDrawable = new ArrayList<Integer>();

	private PopupWindow popup;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case 1:
					Utils.ExitPrgress(getActivity());
					try {
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.l_net_error));
						mPullToRefreshView.onFooterRefreshComplete();
						mPullToRefreshView.onHeaderRefreshComplete();
						if (mPullToRefreshView != null && clubModels.isEmpty()) {
							mPullToRefreshView.setVisibility(View.GONE);
						}
					} catch (Exception e) {
					}

					break;
				case 2:
					Utils.ExitPrgress(getActivity());
					try {

						clubModels.addAll(list);
						// mPullToRefreshView
						// .setLayoutParams(new LinearLayout.LayoutParams(
						// LayoutParams.MATCH_PARENT,
						// LayoutParams.WRAP_CONTENT));
						clubMyClubListAdapter.notifyDataSetChanged();
						mPullToRefreshView.onFooterRefreshComplete();
						mPullToRefreshView.onHeaderRefreshComplete();
						if (mPullToRefreshView != null && !clubModels.isEmpty()) {
							mPullToRefreshView.setVisibility(View.VISIBLE);
						}
					} catch (Exception e) {
					}

					break;
				case 3:
					Utils.ExitPrgress(getActivity());
					try {
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.l_xa10));
						mPullToRefreshView.onFooterRefreshComplete();
						mPullToRefreshView.onHeaderRefreshComplete();
						if (mPullToRefreshView != null && clubModels.isEmpty()) {
							mPullToRefreshView.setVisibility(View.GONE);
						}
					} catch (Exception e) {
					}

					break;
				case 4:
					Utils.ExitPrgress(getActivity());
					try {
						popwindows_Adapter = new Popwindows_Adapter(
								clueTypeModels, getActivity());
						type_list.setAdapter(popwindows_Adapter);
						type_list
								.setOnItemClickListener(new OnItemClickListener() {

									@Override
									public void onItemClick(
											AdapterView<?> arg0, View view,
											int position, long arg3) {
										tid = clueTypeModels.get(position)
												.getId();
										xgridview_TheKeyword
												.setVisibility(View.VISIBLE);
										xgridview_search
												.setVisibility(View.GONE);
										xgridview_TheKeyword
												.setText(clueTypeModels.get(
														position).getName());
										isSouSuo1 = false;
										Page = 1;
										clubModels.clear();
										clubMyClubListAdapter
												.notifyDataSetChanged();
										LoadingInterNet(Page);
										if (popup != null) {
											popup.dismiss();
										}
									}
								});
					} catch (Exception e) {
					}

					break;
				default:
					break;
				}
			} catch (Exception e) {
				   
			}
		}
	};

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		clubModels = new ArrayList<ClubMy_Model>();
		uid = getArguments().getString("uid", "-1");
		fid = getArguments().getString("fid", "-1");
		type = getArguments().getString("type");
		clubMyClubListAdapter = new ClubMyClubListAdapter(getActivity(),
				clubModels);
	}

	@Override
	public void onStart() {
		super.onStart();
		try {
			if (Constants.is_shuaxin) {
				Page = 1;
				if (clubModels != null) {
					clubModels.clear();
				}
				LoadingInterNet(Page);
				Constants.is_shuaxin = false;
			}
		} catch (Exception e) {
		}

	}

	@Override
	public View onCreateView(final LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.xgridview_club, null);

		Page = 1;
		xgridview_search = (LinearLayout) view
				.findViewById(R.id.xgridview_search);
		mPullToRefreshView = (PullToRefreshView) view
				.findViewById(R.id.main_pull_refresh_view_club_area);
		gv = (GridView) view.findViewById(R.id.xgridView11_club);
		xgridview_keyword_kuang = (LinearLayout) view
				.findViewById(R.id.xgridview_keyword_kuang);
		xgridview_keyword_kuang.setVisibility(View.GONE);
		clueTypeModels = new ArrayList<ClueTypeModel>();
		// gv.setXGridViewListener(this);
		gv.setNumColumns(2);
		gv.setPadding(0, DisplayUtil.dip2px(getActivity(), 10),
				DisplayUtil.dip2px(getActivity(), 10),
				DisplayUtil.dip2px(getActivity(), 10));

		gv.setAdapter(clubMyClubListAdapter);

		fragment_club_overview0_btn_type_xgridview = (LinearLayout) view
				.findViewById(R.id.fragment_club_overview0_btn_type_xgridview);
		xgridview_TheKeyword = (TextView) view
				.findViewById(R.id.xgridview_TheKeyword);
		InitPop(fragment_club_overview0_btn_type_xgridview);
		Utils.showPrgress(getActivity());
		LoadingInterNet(Page);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		return view;
	}

	private void InitPop(final View v) {
		fragment_club_overview0_btn_type_xgridview
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						OpenOrClosePopWindows(v);
					}
				});
	}

	/**
	 * 打开或管理悬浮对话框
	 * 
	 * @param inflater
	 * @param v
	 */
	public void OpenOrClosePopWindows(View v) {

		LayoutInflater inflater = LayoutInflater.from(getActivity());
		View root = inflater.inflate(
				R.layout.fragment_club_overview_popwindows, null);
		type_list = (ListView) root.findViewById(R.id.type_list);
		popup = new PopupWindow(root, LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		popup.setBackgroundDrawable(new BitmapDrawable());
		popup.setFocusable(true);
		popup.setTouchable(true);
		popup.setOutsideTouchable(true);
		hadType();
		popup.showAsDropDown(v);
	}

	/**
	 * 显示种类
	 */
	private void hadType() {
		Utils.showPrgress(getActivity());
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("languageType", com.badibadi.mytools.Dialog
						.getSystemLanguageTypegrzx(getActivity()));
				map.put("uid", Utils.getUid(getActivity()));
				map.put("type", "1");
				map.put("cid", "0");
				String acticontent = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "commonality/hadType");
				System.out.println("myclub"+acticontent);
				if (acticontent != null) {
					Results results = Utils.checkResult_NNN(getActivity(),
							acticontent);
					if (results != null && results.getRetmsg() != null
							&& results.isRet()) {
//						   ("我的俱乐部的类别结果是:" + acticontent);
						try {
							clueTypeModels = JSONUtils.getListByJsonString(
									results.getRetmsg(), ClueTypeModel.class);
							System.out.println("wodejulebu"+results.getRetmsg());
							mHandler.sendEmptyMessage(4);
						} catch (JSONException e) {
							   
						}
					} else {
						mHandler.sendEmptyMessage(3);
					}
				} else {
					mHandler.sendEmptyMessage(1);
				}
			}
		});
	}

	/**
	 * 俱乐部的列表显示
	 * 
	 * @param $uid
	 *            ;//用户id 当自己查看自己的俱乐部时 分以下两个情况 第一种 @param $tid;//俱乐部的类型id
	 * @param $type
	 *            ;// 0:最新，1：最热，2：自创 第二种
	 * @param $searchName
	 *            ;//搜索关键字 (一次只能完成其中一种的筛选) 一个用户查看 另一个用户的俱乐部时
	 * @param $fid
	 *            ;//朋友id
	 * @param $page
	 *            ;//第几页 $pageNum;//每页显示条数
	 */
	private void LoadingInterNet(final int page) {
		//    
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
				//    
				if (fid.equals("-1") != true) {
					map.put("fid", fid);
				}
				if (tid != null) {
					map.put("tid", tid);
				}
				if (searchName != null) {
					map.put("searchName", searchName);
				}
				map.put("type", type);
				map.put("page", page);
				map.put("pageNum", pageNum);
				//    (map.toString());
//				   
				String invite_content = Utils.sendRequest(map,
						Constants.BadiUrl + "club");
				System.out.println("shuju"+invite_content);
				//    
				if (invite_content != null) {
					Results results = Utils.checkResult_NNN(getActivity(),
							invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   
//						   ("我是解析出来的数据:" + results.getRetmsg());
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(), ClubMy_Model.class);
							mHandler.sendEmptyMessage(2);
						} catch (Exception e) {
							   
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						mHandler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					mHandler.sendEmptyMessage(1);
				}

			}
		});
	}

	public static MyClubFragment0 getInstance() {
		if (myClubFragment0 == null) {
			return new MyClubFragment0();
		}
		return myClubFragment0;
	}

	/**
	 * 点击回退键之后的操作回退到上一级
	 * 
	 * @param get
	 */
	public void getSearchIsReturnUp(getFragmentData get) {
		get.getIsReturnUp(isReturnUp);
		//    ("状态为:" + ll_search.getVisibility());
		if (xgridview_search.getVisibility() == 8) {// 隐藏
			//    ("隐藏状态，变为显示");
			// searchName = null;
			xgridview_search.setVisibility(View.VISIBLE);
			xgridview_TheKeyword.setVisibility(View.GONE);
			Page = 1;
			tid = null;
			clubModels.clear();
			clubMyClubListAdapter.notifyDataSetChanged();
			LoadingInterNet(Page);
		} else {
			((getActivity())).finish();
			getActivity().overridePendingTransition(R.anim.slide_left2,
					R.anim.slide_right2);
		}
	}

	public interface getFragmentData {
		// 是否返回到上一级returnSearch
		void getIsReturnUp(boolean isReturn);
	}

	/**
	 * 打开或管理悬浮对话框
	 * 
	 * @param inflater
	 * @param v
	 */
	public void OpenOrClosePopWindows(LayoutInflater inflater, View v) {
		if (popup == null) {
			View root = inflater.inflate(
					R.layout.fragment_club_overview_popwindows, null);
			popup = new PopupWindow(root, 300, 360);
			popup.showAsDropDown(v);
		} else {
			popup.dismiss();
			popup = null;
		}
	}

	// @Override
	// public void OnLoadMore() {
	// //    
	//
	// }

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		LoadingInterNet(++Page);

	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		Page = 1;
		if (clubModels != null) {
			clubModels.clear();
		}
		LoadingInterNet(Page);

	}
}
